﻿using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using DG.Tweening;
using Resources.Scripts.Socket.MyChat.Manager;
using Resources.Scripts.Socket.MyChat.Protocol;
using Resources.Scripts.Utils;
using TMPro;
using UnityEngine;

namespace Resources.Scripts.Socket.MyChat.Client
{
    public class NetClient : MonoBehaviour
    {
        public static NetClient Instance;
        public string ip;
        public string port;
        public int userId;
        public string userName;
        private BinaryReader br;
        private BinaryWriter bw;
        
        private TcpClient client;

        private CancellationTokenSource cts;
        private MessageFormatSplit mfs ;

        public ConcurrentQueue<ChatMessage> ReData;

        ////  接受消息提示
        //public GameObject showTip;

        public Action<string> ShowTip; 

        // public Action Cancel { private get; set; }
        private void Start()
        {
            Init();
        }

        private void Init()
        {
            try
            {
                //client = new TcpClient(new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
                client = new TcpClient();
                client.Connect(new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));

            }
            catch(SocketException e)
            {
                Debug.Log(string.Format("链接服务器失败! 错误信息 ："+e.Message));
                return;
            }

            Debug.Log("Connect Success!");

            cts = new CancellationTokenSource();
            ReData = new();

            NetworkStream networkStream = client.GetStream();
            br = new BinaryReader(networkStream);
            bw = new BinaryWriter(networkStream);

            mfs = new MessageFormatSplit();
            
            SendLoginMessage();
            
            // Task.Run(() => Receive(cts));
            ThreadPool.QueueUserWorkItem((obj) => Receive(cts));
        }

        public void SendLoginMessage()
        {
            string msg = ((int)ChatChannel.Login).ToString("D8") + "{"+ userId + ","+userName+"}";
            bw.Write(msg);
            bw.Flush();
        }

        private void Awake()
        {
            if (Instance != null)
            {
                Destroy(gameObject);
                return;
            }

            Instance = this;
        }

        private void OnDestroy()
        {
            Cancel();
        }

        public void SendMessage(ChatMessage message)
        {
            bw.Write(message.ToString());
            bw.Flush();
        }

        public void MySendMessage(string message)
        {
            bw.Write(message);
            bw.Flush();
        }

        public ChatMessage ReceiveMessage()
        {
            string receiveData;
            try
            {
                receiveData = br.ReadString();
            }
            catch (Exception e)
            {
                Debug.Log("与服务器失去联系,异常为: "+e.Message);
                return null;
            }

            Debug.Log("has Data Receive : " + receiveData);
            
            // ShowTip?.Invoke(receiveData);
            //ShowTip(receiveData);
            Debug.Log("Show Tip");


            ChatChannel channel = default;
            try
            {
                mfs.Message = receiveData;
                channel = mfs.GetChatChannel();
            }
            catch
            {
                Debug.Log("At 135 line");
            }

            User user;
            try
            {
                user = mfs.GetSenderUser();
            }
            catch
            {
                Debug.Log("user format error !");
                return null;
            }
            Debug.Log("User Id : " + user.Id);
            Debug.Log("User Name : "+userName);

            string message;
            ChatMessage chatMessage = null;
            try
            {
                message = mfs.GetMessage();
                chatMessage = new ChatMessage();
                chatMessage.Message = message;
            }
            catch
            {
                Debug.Log("At 160 line");
            }

            try
            {
                chatMessage.FromId = user.Id;
                chatMessage.FromName = user.Name;
                chatMessage.Channel = channel;
            }
            catch
            {
                
                Debug.Log("复制失败!");
            }




            return chatMessage;
            // return NetMessage.FormString(receiveData);
        }

        private void Receive(CancellationTokenSource c)
        {
            while (cts.Token.IsCancellationRequested == false)
            {

                var message = ReceiveMessage();

                // ChatManager.Instance.AddMessage(message);
                // ReData.Enqueue(message);
                Debug.Log("入队！");
            }
        }

        //public void ShowTip(string msg) {
        //    showTip.GetComponentInChildren<TMP_Text>().text = msg;
        //    showTip.SetActive(true);
        //    Invoke("CloseTip", 10f);
        //}

        //public void CloseTip() {
        //    showTip.SetActive(false);
        //}

        private void Cancel()
        {
            cts.Cancel();
        }

        #region 消息处理

        

        #endregion
    }
}